package consul.allinone.regist;

import com.orbitz.consul.AgentClient;
import com.orbitz.consul.Consul;
import com.orbitz.consul.model.agent.ImmutableRegCheck;
import com.orbitz.consul.model.agent.ImmutableRegistration;
import consul.allinone.RpcURL;

/**
 * Title:
 * Description:
 * Author:吉
 * Since:2018/4/13
 * Version:1.1.0
 */
public class ConsulRegistService extends AbstractConsulService implements RegistryService {


    private String registryHost;

    private Integer registryPort;

    public ConsulRegistService(String regsitIp, Integer registPort) {
        this.registryHost = regsitIp;
        this.registryPort = registPort;
    }


    @Override
    public void register(RpcURL url) {
        Consul consul = this.buildConsul(registryHost, registryPort);
        AgentClient agent = consul.agentClient();
        ImmutableRegCheck check = ImmutableRegCheck.builder()
                .http("http://" + url.getHost() + ":" + url.getPort())
                .interval(CONSUL_HEALTH_INTERVAL)
                .build();
        System.out.println("http://" + url.getHost() + ":" + url.getPort());
        ImmutableRegistration.Builder builder = ImmutableRegistration.builder();
        builder.id(url.getId()).name(url.getServiceName()).addTags(SERVICE_TAGS).address(url.getHost()).port(url.getPort())
                .addChecks(check);
        agent.register(builder.build());
    }

    @Override
    public void unregister(RpcURL url) {
        Consul consul = this.buildConsul(registryHost, registryPort);
        AgentClient agent = consul.agentClient();
        agent.deregister(url.getId());
    }

}
